package org.luxor.commons.core.utils;

import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 登陆密码工具
 *
 * @author yanxinming
 */
public class PassWordUtils {

    private volatile static PasswordEncoder passwordEncoder;

    public static PasswordEncoder getInstance() {
        if (passwordEncoder == null) {
            synchronized (PassWordUtils.class) {
                if (passwordEncoder == null) {
                    passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
                    return passwordEncoder;
                }
            }
        }
        return passwordEncoder;
    }

    /**
     * 加密
     *
     * @param rawPassword 明文密码
     * @return
     */
    public static String encode(String rawPassword) {
        return PassWordUtils.getInstance().encode(rawPassword);
    }

    /**
     * 校验密码
     *
     * @param rawPassword     明文密码
     * @param encodedPassword 加密后的密码
     * @return 如果校验通过，则返回真
     */
    public static Boolean matches(String rawPassword, String encodedPassword) {
        return PassWordUtils.getInstance().matches(rawPassword, encodedPassword);
    }

    /**
     * 加密+盐
     *
     * @param rawPassword 明文密码
     * @param slat        盐
     * @return
     */
    public static String encode(String rawPassword, String slat) {
        String password = rawPassword(rawPassword, slat);
        return PassWordUtils.getInstance().encode(password);
    }

    /**
     * 校验密码+盐
     *
     * @param rawPassword     明文密码
     * @param slat            盐
     * @param encodedPassword 加密后的密码
     * @return 如果校验通过，则返回真
     */
    public static Boolean matches(String rawPassword, String slat, String encodedPassword) {
        String password = rawPassword(rawPassword, slat);
        return PassWordUtils.getInstance().matches(password, encodedPassword);
    }

    /**
     * 组装完整的密码格式
     *
     * @param password 明文密码
     * @param slat     盐
     * @return
     */
    public static String rawPassword(String password, String slat) {
        if (StringUtils.isBlank(slat)) {
            return password;
        } else {
            return String.format("%s-{%s}", password, slat);
        }
    }
}